import { useState, useEffect } from 'react';
import { Upload, message, Button } from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import './index.less';
import API from '@/api';
function UploadList({
  uploadUrl,
  options,
  onChange,
  defaultFiles,
  downloadUrl,
}) {
  const [fileList, setList] = useState([]);
  const beforeUpload = (file, list) => {
    let isIncudeType = true;
    if (options.fileTypes) {
      isIncudeType = options.fileTypes.includes(file.type);
      if (!isIncudeType) {
        message.error('只能上传 ' + options.acceptMessage + ' 格式!');
      }
    }
    const isMaxSize = file.size / 1024 / 1024 < options.maxSize;
    if (!isMaxSize) {
      message.error('文件大小不能超过' + options.maxSize + 'M!');
    }
    if (file.size == 0) {
      message.error('不能上传空文件');
    }
    const length = fileList.length + list.length;
    console.log(length);
    const isMax = length < options.maxNum + 1;
    console.log(isMax);
    if (!isMax) {
      message.destroy();
      message.error('文件数量不能超过' + options.maxNum + '个！');
    }
    return isIncudeType && isMaxSize && isMax && file.size > 0
      ? true
      : Upload.LIST_IGNORE;
  };
  const handleUpload = (info) => {
    setList([...info.fileList]);
    const value = info.fileList.map((x) => {
      if (x.response?.t) {
        return {
          originalFileName: x.response.t.originalFileName,
          fileName: x.response.t.fileName,
          url: x.response.t.url,
        };
      }
    });
    onChange(value);
  };

  useEffect(() => {
    const defaultFileList = defaultFiles
      ? defaultFiles.map((x) => ({
          uid: x.id,
          name: x.originalFileName,
          status: 'done',
          url: x.url,
          response: {
            t: {
              originalFileName: x.originalFileName,
              fileName: x.fileName,
            },
          },
        }))
      : [];
    setList(defaultFileList);
  }, [defaultFiles]);

  const downloadFn = (file) => {
    if (file.response?.t) {
      const { fileName, originalFileName } = file.response.t;
      API.downloadFn(downloadUrl, { fileName, originalFileName });
    }
  };
  const showUploadList = {
    showDownloadIcon: true,
    downloadIcon: <DownloadOutlined />,
    showRemoveIcon: true,
  };
  const jwt = localStorage.getItem('jwt');
  return (
    <Upload
      multiple
      headers={{ jwt }}
      action={'/jiaotong' + uploadUrl}
      accept={options.accept}
      beforeUpload={beforeUpload}
      fileList={fileList}
      onChange={handleUpload}
      showUploadList={showUploadList}
      className="upload-x"
      onDownload={downloadUrl && downloadFn}
      onPreview={downloadUrl && downloadFn}
    >
      <Button type="primary" icon={<UploadOutlined />}>
        上传
      </Button>
    </Upload>
  );
}
export default UploadList;
